<template>
	<div class="edit-work-flow">
		<el-dialog :title="showDetail ? '人工坐席工作流' : '编辑人工坐席工作流'" :visible.sync="showEditWorkFlow" width="50%" :before-close="closeEditWorkFlow">
			<el-form :model="workFlowForm" ref="ruleForm" label-width="100px">
				<el-form-item label="工作流名称" prop="workFlowName.value.name" label-width="100px" :rules="rules.workFlowNameRules">
					<el-input v-model="workFlowForm.workFlowName.value.name" :disabled="showDetail" placeholder="请输入工作流名称" class="el-input" ref="input"></el-input>
				</el-form-item>
				<div v-for="(item, index) in workFlowForm.initWorkFLowData.value" :key="index">
					<el-form-item class="prop" :label="`流程节点${index + 1} `" :prop="'initWorkFLowData.value.' + index + '.name'" :rules="rules.workFlowConentRules" label-width="100px">
						<el-input v-model="item.name" :disabled="showDetail" placeholder="请输入当前需要完成的流程节点名称" maxlength="16"></el-input>
						<el-checkbox v-model="item.isDot" :disabled="showDetail" :label="item.isDot" class="pleft40">视频打点</el-checkbox>
						<i class="el-icon-close" @click="removeProp(index)" v-show="workFlowForm.initWorkFLowData.value.length > 1" v-if="!showDetail"></i>
					</el-form-item>
					<el-form-item class="prop" :prop="'initWorkFLowData.value.' + index + '.content'" :rules="rules.workFlowTipsRules" label-width="100px">
						<ZcoTextarea
							:value="item.content"
							placeholder="请输入当前流程节点的话术提示"
							:showDetail="showDetail"
							maxlength="2000"
							type="textarea"
							:autosize="{ minRows: 1.5, maxRows: 2 }"
							@input="e => input(e, index)"
							:id="'humanflow_' + index + '_content'"
						/>
						<span class="add" @click="e => onAddVariable(index)" v-if="!showDetail">+</span>
					</el-form-item>
				</div>

				<el-form-item class="pleft10">
					<el-button @click="addProps" v-if="!showDetail">添加流程</el-button>
				</el-form-item>
				<div class="btn" v-if="!showDetail">
					<el-button @click="closeEditWorkFlow">取消</el-button>
					<el-button type="primary" @click="getEditWorkFlow">确认</el-button>
				</div>
			</el-form>
		</el-dialog>
		<!-- 用户变量 -->
		<UserAttribute v-if="isShowUserAttribute" :dialogVisible="isShowUserAttribute" taskId="" @on-ok="onChosseUserAttribute" @on-cancel="isShowUserAttribute = false" />
		<span tabindex="-1" ref="invisibleFocus"></span>
	</div>
</template>

<script>
import { mapState } from 'vuex';
import { validateWorkFlowName, validateFlowConent } from '@/utils/formValidate';
import ZcoTextarea from '../AiWorkFlow/components/TinymceTextarea.vue';
import UserAttribute from '../AiWorkFlow/AiTemplateView/UserAttribute.vue';
import { insertStr } from '@/utils/tool';

export default {
	components: { ZcoTextarea, UserAttribute },
	props: {
		showEditWorkFlow: {
			type: Boolean,
			required: true,
			default: () => false
		},
		editData: {
			type: Object,
			required: true,
			default: () => {}
		},
		showDetail: {
			type: Boolean,
			default: () => false,
			required: true
		}
	},
	data() {
		return {
			workFlowForm: {
				// 初始化工作流数据
				initWorkFLowData: {
					value: [
						{
							content: '',
							isDot: 0,
							name: ''
						}
					]
				},
				// 工作流名称
				workFlowName: {
					op: 'replace',
					path: '/flow',
					value: {
						name: ''
					}
				},
				// 工作流步骤
				editWorkFlowSteps: {
					op: 'replace',
					path: '/steps',
					value: [
						{
							content: '',
							isDot: 0,
							name: ''
						}
					]
				},
				// 工作流步骤
				removeWorkFlowSteps: {
					op: 'remove',
					path: '/steps',
					value: []
				},
				// 新增工作步骤
				addWorkFlowSteps: {
					op: 'add',
					path: '/steps',
					value: [
						{
							content: '',
							isDot: 0,
							name: ''
						}
					]
				},
				variables: {
					key: '',
					name: ''
				}
			},
			// 当前选中的变量
			currentVariable: [],
			// 默认初始化变量数组
			defualtVariables: [],
			// 勾选的变量
			checkedVaribles: [],
			isShowUserAttribute: false,
			currentVariableInput: '',
			// 校验规则
			rules: {
				workFlowNameRules: [
					{ required: true, message: '请输入工作流名称', trigger: ['blur'] },
					{ validator: validateWorkFlowName, trigger: ['change'] }
				],
				workFlowConentRules: [
					{ required: true, message: '请输入流程节点', trigger: ['blur'] },
					{ validator: validateFlowConent, trigger: ['blur'] }
				],
				workFlowTipsRules: [
					{ required: true, message: '请输入流程节点的话术提示', trigger: ['blur'] },
					// { validator: validateFlowTips, trigger: ['blur'] }
				]
			}
		};
	},
	computed: {
		...mapState({
			editWorkFlow: state => state.editWorkFlow.editWorkFlow
		})
	},
	mounted() {
		if (this.showDetail) {
			setTimeout(() => {
				this.$refs.invisibleFocus.focus();
			}, 0);
		}
		this.initAddWorkFlow();
		console.log(this.showDetail);
	},

	methods: {
		// 新增工作流初始化
		initAddWorkFlow() {
			this.workFlowForm.workFlowName.value.name = JSON.parse(JSON.stringify(this.editWorkFlow.name));
			this.workFlowForm.initWorkFLowData.value = JSON.parse(JSON.stringify(this.editWorkFlow.steps));
			this.workFlowForm.variables = { key: '', name: '' };
			console.log('initAddWorkFlow', this.workFlowForm.initWorkFLowData.value);
		},
		// 关闭新增工作流模态框
		closeEditWorkFlow() {
			this.workFlowForm.removeWorkFlowSteps.value = [];
			this.$emit('closeEditWorkFlow');
		},
		getEditWorkFlow() {
			let data = [];
			const steps = this.workFlowForm.initWorkFLowData.value
				.map(step => {
					return { content: step.content, isDot: step.isDot, name: step.name };
				});
			// this.workFlowForm.editWorkFlowSteps.value = this.workFlowForm.initWorkFLowData.value.filter(item => item.id);
			// data.push(
			// 	this.workFlowForm.workFlowName,
			// 	this.workFlowForm.removeWorkFlowSteps,
			// 	this.workFlowForm.addWorkFlowSteps,
			// 	this.workFlowForm.editWorkFlowSteps,
			// );
			// {
			// 	"name":"名称25",
			// 	"steps": [
			// 		{
			// 			"name":"节点名称",
			// 			"content":"话术提示",
			// 			"isDot": false
			// 		},
			// 		{
			// 			"name":"节点名称1",
			// 			"content":"话术提示1",
			// 			"isDot": true
			// 		}

			// 	]
			// }
			data = {
				name: this.workFlowForm.workFlowName.value.name,
				steps: steps
			}
			this.$refs.ruleForm.validate(valid => {
				console.log('validate', valid, this.workFlowForm.initWorkFLowData.value);
				if (valid) {
					this.$emit('getEditWorkFlow', data);
				} else {
					return false;
				}
			});
		},
		// 移除流程
		removeProp(index) {
			// 对于移除元素，必须要有 ID
			this.workFlowForm.initWorkFLowData.value.forEach((item, curIndex) => {
				if (index === curIndex && item.id) {
					this.workFlowForm.removeWorkFlowSteps.value.push(item);
				}
			});
			this.workFlowForm.initWorkFLowData.value.splice(index, 1);
			console.log(this.workFlowForm.removeWorkFlowSteps.value);
		},
		// 增加流程
		addProps() {
			this.workFlowForm.initWorkFLowData.value.push({ content: '', isDot: false, name: '' });
			this.currentVariable = [];
		},
		input(e, index) {
			// console.log('input', e, index);
			this.workFlowForm.initWorkFLowData.value[index].content = e.trim();
			this.$refs.ruleForm.validateField('initWorkFLowData.value.' + index + '.content');
		},
		onAddVariable(index) {
			this.currentVariableInput = 'humanflow_' + index + '_content';
			this.isShowUserAttribute = true;
		},
		// 变量插入
		onChosseUserAttribute(data, businessData) {
			console.log('onChosseUserAttribute', this.currentVariableInput, data, businessData);
			let variable = '';
			let wordsDom = document.getElementById(this.currentVariableInput);
			if (!wordsDom) {
				wordsDom = document.getElementById(this.currentVariableInput + 'textarea');
			}
			if (data && data.name) {
				// 客户信息_角色名_变量名
				variable = `{{客户信息_${data.bizscenario_role.name}_${data.name}_${data.id}}}`;
				insertStr('', wordsDom, variable);
			}
			if (businessData && businessData.name) {
				// 业务信息_变量名
				variable = `{{业务信息_${businessData.name}_${businessData.id}}}`;
				insertStr('', wordsDom, variable);
			}

			this.isShowUserAttribute = false;
		}
	}
};
</script>

<style lang="less">
.edit-work-flow {
	.el-checkbox__inner {
		border-radius: 50%;
	}
}

.global-addvariable {
	.addvariable {
		.el-form-item__content {
			width: 400px;
		}

		background-color: #f8f8f8;

		.el-form-item:nth-child(1) {
			padding-top: 20px;
		}

		.el-form-item:nth-child(2) {
			padding-top: -30px;
		}

		.addvariable_fontsize {
			display: block;
			margin-left: 270px;
			padding-bottom: 20px;
		}

		.addvariable_fontsize_jianju {
			padding: 0 43px;
		}
	}
}
</style>

<style lang="less" scoped>
.edit-work-flow {
	.head {
		padding: 20px 0;
	}

	.btn {
		text-align: right;
	}

	.prop {
		width: 100%;

		.el-input {
			width: 90%;
		}
	}

	.el-icon-close {
		padding-left: 10px;
		cursor: pointer;
	}

	.el-input {
		width: 280px !important;
	}

	.add {
		position: absolute;
		right: 10px;
		top: 10px;
		color: #888;
		font-size: 20px;
		height: 20px;
		line-height: 20px;
		bottom: 20px;
		cursor: pointer;
	}

	.pleft40 {
		padding-left: 40px;
	}

	.pleft20 {
		padding-left: 20px;
	}

	.pleft10 {
		padding-left: 10px;
	}

	.right {
		margin-left: 100px;
	}

	.mtop {
		margin-top: 10px;
	}

	.pleft10 {
		padding-left: 10px;
	}

	.addvariable {
		background-color: #f8f8f8;

		.el-form-item:nth-child(1) {
			padding-top: 20px;
		}

		.el-form-item:nth-child(2) {
			padding-top: -30px;
		}
	}

	.addvariable_input {
		width: 300px;
	}

	.addvariable_btn {
		text-align: right;
		margin-top: 40px;
	}

	.addvariable_fontsize {
		display: block;
		margin-left: 270px;
		padding-bottom: 20px;
	}

	.addvariable_fontsize_jianju {
		padding: 0 43px;
	}

	.el-checkbox-group {
		margin-top: -30px;
	}
}
</style>
